import JSEncrypt from 'jsencrypt';

// 添加 console.log 验证 JSEncrypt
// console.log(JSEncrypt); // 应该输出 JSEncrypt 构造函数

// const baseURL = 'https://wygw.wuyin298.com/'
// const ossReqPath = "https://jxoss.yunqz.cn";

const baseURL = 'http://127.0.0.1:9003/'
const ossReqPath = "http://127.0.0.1:9002";

const ossKey = 'MemNocrBLk3sv4Xl5zrjmb4Fv81j6GT5';
const cpId = "wuyou";



/**
 * 生成请求签名
 */
export function genHmac() {
	// console.info("genHmac.begin");
	const encrypt = new JSEncrypt()
	// 替换成你的公钥
	const publicKey =
		`MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbPTlB63OSW-2N9tIArI3sJ1eVwwin7JPH4RaWdMqEa1FjKyuPB-0njv6Ldk64kqEqfihRh6ryH9GF1uqQZZdya7krxPoO6SoXKaBDZAo63Bz-iz-1LQqJDll3H0TtuJuxB-GJDnFGM8KBh51P4Cpd6vPhYC4GPqg7aaraON8hqQIDAQAB`;
	encrypt.setPublicKey(publicKey);
	// 获取用户信息
	const userInfo = uni.getStorageSync('USER_SESSION') || {};
	const tokenId = uni.getStorageSync('TOKENID_SESSION') || '';
	// 构建原始签名字符串
	const originalSignature = `${userInfo.userId}:${tokenId}:${userInfo.cpId}`;
	// 加密
	const signature = encrypt.encrypt(originalSignature);
	// console.info("genHmac.signature:"+signature);
	return signature
}

/**
 * 请求
 * @param url
 * @param submitType
 * @param data
 * @param successCallback
 * @param isSucAlert
 */
export function httpRequest(options) {
	const { url, submitType, data = {}, successCallback, isSucAlert } = options;
	const userInfo = uni.getStorageSync('USER_SESSION');
	if (!userInfo) {
		uni.clearStorage();
		uni.reLaunch({
			url: '/pages/login/login'
		});
		return;
	}
	// 生成签名
	const hmac = genHmac();
	uni.showLoading({
		title: '加载中...',
		mask: true
	});
	// console.info("url:"+baseURL + url);
	// console.info("data:"+JSON.stringify(data));
	// console.info("submitType:"+submitType);
	// console.info("hmac:"+hmac);
	uni.request({
		url: baseURL + url,
		dataType: "json",
		data: data,
		method: submitType,
		header: {
			'hmac': hmac
		},
		success: (res) => {
			uni.hideLoading();
			// 响应成功
			if (res.data.statusCode != "00000") {
				console.info("a6");
				// 处理失败
				if (res.data.statusCode === '30001' || res.data.statusCode === '30002') {
					// 令牌失效
					uni.showToast({
						title: '登录过期了，请重新登录',
						icon: 'loading',
						duration: 1500,
						success: function() {
							uni.clearStorage();
							uni.reLaunch({
								url: '/pages/login/login'
							});
							return;
						}
					});
				}
				// 其它错误
				uni.showToast({
					title: res.data.statusDesc,
					icon: 'none'
				});
				return;
			}
			// 处理成功
			if (successCallback && typeof successCallback === 'function') {
				successCallback(res.data); // 调用回调函数
			} else if (isSucAlert=='y') {
				uni.showToast({
					title: '操作成功',
					icon: 'none'
				});
			}
		},
		fail: (err) => {
			uni.hideLoading();
			uni.showToast({
				title: '网络错误，请检查网络连接',
				icon: 'none'
			});
		}
	});
}


export function httpRequestNoLogin(options) {
    const { url, submitType, data = {}, successCallback, isSucAlert } = options;
    // 生成签名
    uni.showLoading({
        title: '加载中...',
        mask: true
    });
    // console.info("url:"+baseURL + url);
    // console.info("data:"+JSON.stringify(data));
    // console.info("submitType:"+submitType);
    // console.info("hmac:"+hmac);
    uni.request({
        url: baseURL + url,
        dataType: "json",
        data: data,
        method: submitType,
        success: (res) => {
            uni.hideLoading();
            // 响应成功
            if (res.data.statusCode != "00000") {
                // 其它错误
                uni.showToast({
                    title: res.data.statusDesc,
                    icon: 'none'
                });
                return;
            }
            // 处理成功
            if (successCallback && typeof successCallback === 'function') {
                successCallback(res.data); // 调用回调函数
            } else if (isSucAlert=='y') {
                uni.showToast({
                    title: '操作成功',
                    icon: 'none'
                });
            }
        },
        fail: (err) => {
            uni.hideLoading();
            uni.showToast({
                title: '网络错误，请检查网络连接',
                icon: 'none'
            });
        }
    });
}

/**
 * 获取分页数据
 * @param {String} url - 请求地址
 * @param {Object} params - 请求参数
 * @param {Number} page - 当前页码
 * @param {Number} pageSize - 每页大小
 * @returns {Promise} - 返回分页数据的 Promise
 */
export function fetchPaginatedData(url, params = {}, page = 1, pageSize = 10) {
	return new Promise((resolve, reject) => {
		// 添加分页参数
		params.page = page;
		params.pageSize = pageSize;

		const hmac = genHmac();
		uni.showLoading({
			title: '加载中...',
			mask: true
		});

		uni.request({
			url: baseURL + url,
			method: 'POST',
			data: params,
			header: {
				'hmac': hmac
			},
			success: (res) => {
				uni.hideLoading();
				if (res.data.statusCode === "00000") {
					resolve(res.data.rspData); // 返回分页数据
				} else {
					if (res.data.statusCode === '30001' || res.data.statusCode === '30002') {
						// 令牌失效
						uni.showToast({
							title: '登录过期了，请重新登录',
							icon: 'loading',
							duration: 1500,
							success: function() {
								uni.clearStorage();
								uni.reLaunch({
									url: '/pages/login/login'
								});
								return;
							}
						});
					}
					// 其它错误
					uni.showToast({
						title: res.data.statusDesc,
						icon: 'none'
					});
					return;
				}
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showToast({
					title: '网络错误，请检查网络连接',
					icon: 'none'
				});
			}
		});
	});
}

export function fetchPaginatedDataNoLogin(url, params = {}, page = 1, pageSize = 10) {
    return new Promise((resolve, reject) => {
        // 添加分页参数
        params.page = page;
        params.pageSize = pageSize;
        uni.showLoading({
            title: '加载中...',
            mask: true
        });

        uni.request({
            url: baseURL + url,
            method: 'POST',
            data: params,
            success: (res) => {
                uni.hideLoading();
                if (res.data.statusCode === "00000") {
                    resolve(res.data.rspData); // 返回分页数据
                } else {
                    // 其它错误
                    uni.showToast({
                        title: res.data.statusDesc,
                        icon: 'none'
                    });
                    return;
                }
            },
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                    title: '网络错误，请检查网络连接',
                    icon: 'none'
                });
            }
        });
    });
}

export function uploadSingleFile(file) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: ossReqPath + '/fileController/uploadImg',
			filePath: file.path,
			name: 'img',
			formData: {
				cpId: cpId
			},
			header: {
				"hmac": ossKey
			},
			success: (result) => {
				try {
					var res = JSON.parse(result.data);
					if (res.statusCode != "00000") {
						if (res.statusCode === '30001' || res.statusCode === '30002') {
							uni.showToast({
								title: '登录过期了，请重新登录',
								icon: 'loading',
								duration: 1500,
								success: function() {
									uni.clearStorage();
									uni.reLaunch({
										url: '/pages/login/login'
									});
									return;
								}
							});
						}
						uni.showToast({
							title: res.statusDesc,
							icon: 'none'
						});
						reject(res);
						return;
					}
					resolve(res);
				} catch (e) {
					reject(new Error('响应解析失败'));
				}
			},
			fail: (err) => {
				reject(new Error('网络请求失败'));
			}
		});
	});
}

export default {
	genHmac,
	httpRequest,
    httpRequestNoLogin,
	fetchPaginatedData,
    fetchPaginatedDataNoLogin,
	uploadSingleFile
};